package com.example.hlsdemo.controller;

import com.example.hlsdemo.entity.VideoInfo;
import com.example.hlsdemo.service.impl.VideoServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/api/videos")
public class VideoController {

    @Autowired
    private VideoServiceImpl videoServiceImpl;


    /**
     * 上传视频（同步处理）
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public ResponseEntity<?> uploadVideo(@RequestParam("video") MultipartFile file) {
        log.info("同步上传视频，文件名: {}", file.getOriginalFilename());
        String videoId;
        try {
            videoId = videoServiceImpl.uploadAndConvertVideo(file);
            return ResponseEntity.ok(
                    Map.of(
                            "videoId", videoId,
                            "status", "PROCESSING",
                            "message", "视频上传成功"
                    )
            );
        } catch (Exception e) {
            log.error("同步上传文件失败", e);
            return ResponseEntity.badRequest().body(Map.of("错误信息", e.getMessage()));
        }
    }

    /**
     * 上传视频（异步处理）
     * 快速返回结果，后台异步进行转码
     *
     * @param file
     * @return
     */
    @PostMapping("/upload/async")
    public ResponseEntity<?> uploadVideoAsync(@RequestParam("video") MultipartFile file) {
        log.info("异步上传视频，文件名: {}", file.getOriginalFilename());
        try {
            String videoId = videoServiceImpl.uploadVideoAsync(file);
            return ResponseEntity.ok(Map.of(
                    "videoId", videoId,
                    "status", "PROCESSING",
                    "message", "视频上传成功，转码处理中"
            ));
        } catch (Exception e) {
            log.error("异步视频上传失败", e);
            return ResponseEntity.badRequest().body(Map.of("视频异步转码上传发生错误", e.getMessage()));
        }
    }


    /**
     * 获取视频处理状态
     */
    @GetMapping("/{videoId}/status")
    public ResponseEntity<?> getVideoStatus(@PathVariable String videoId) {
        log.info("获取视频状态，videoId: {}", videoId);
        try {
            VideoInfo videoInfo = videoServiceImpl.getVideoInfo(videoId);
            if (videoInfo == null) {
                return ResponseEntity.notFound().build();
            }

            return ResponseEntity.ok(Map.of(
                    "videoId", videoId,
                    "status", videoInfo.getStatus(),
                    "originalReady", videoInfo.getOriginalM3u8Path() != null,
                    "lowReady", videoInfo.getLowM3u8Path() != null,
                    "midReady", videoInfo.getMidM3u8Path() != null,
                    "highReady", videoInfo.getHighM3u8Path() != null
            ));
        } catch (Exception e) {
            log.error("获取视频状态失败", e);
            return ResponseEntity.badRequest().body(Map.of("error", e.getMessage()));
        }
    }

    @GetMapping("/list")
    public ResponseEntity<List<VideoInfo>> getAllVideos() {
        log.info("获取视频列表");
        try {
            List<VideoInfo> videos = videoServiceImpl.getAllVideos();
            return ResponseEntity.ok(videos);
        } catch (Exception e) {
            log.error("获取视频列表失败", e);
            return ResponseEntity.badRequest().build();
        }
    }

    /**
     * 获取指定清晰度的播放列表
     * 支持：original(原始)、low(低清)、mid(中清)、high(高清)
     * 如果请求的清晰度不可用，会返回可用的最高清晰度
     */
    @GetMapping("/{videoId}/playlist_{quality}")
    public ResponseEntity<byte[]> getPlaylist(@PathVariable String videoId, @PathVariable String quality) {
        log.info("获取视频播放列表，videoId: {}, quality: {}", videoId, quality);
        try {
            VideoInfo videoInfo = videoServiceImpl.getVideoInfo(videoId);
            if (videoInfo == null) {
                return ResponseEntity.notFound().build();
            }

            String playlistName = getString(quality, videoInfo);

            if (playlistName == null) {
                return ResponseEntity.notFound().build();
            }

            byte[] playlist = videoServiceImpl.getPlaylist(videoId, playlistName);
            return ResponseEntity.ok()
                    .contentType(MediaType.parseMediaType("application/vnd.apple.mpegurl"))
                    .body(playlist);
        } catch (Exception e) {
            log.error("获取播放列表失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    private static String getString(String quality, VideoInfo videoInfo) {
        String playlistName;
        // 如果视频还在处理中，返回原始视频地址
        if ("PROCESSING".equals(videoInfo.getStatus())) {
            playlistName = videoInfo.getOriginalM3u8Path();
        } else {
            // 根据请求的清晰度返回对应的播放列表
            switch (quality) {
                case "low":
                    playlistName = videoInfo.getLowM3u8Path();
                    break;
                case "mid":
                    playlistName = videoInfo.getMidM3u8Path();
                    break;
                case "high":
                    playlistName = videoInfo.getHighM3u8Path();
                    break;
                default:
                    playlistName = videoInfo.getHighM3u8Path(); // 默认返回高清版本
            }
        }
        return playlistName;
    }

    @GetMapping("/{videoId}/{filename}")
    public ResponseEntity<byte[]> getVideoFile(
            @PathVariable String videoId,
            @PathVariable String filename) {
        log.info("获取视频文件，videoId: {}, filename: {}", videoId, filename);
        try {
            return ResponseEntity.ok()
                    .header("Content-Type", "video/MP2T")
                    .body(videoServiceImpl.getVideoFile(videoId, filename));
        } catch (Exception e) {
            log.error("获取视频文件失败", e);
            return ResponseEntity.notFound().build();
        }
    }
} 